package com.alibaba.cloud.base.business.order.service.impl;

import com.alibaba.cloud.base.business.order.dao.BasOrderMapper;
import com.alibaba.cloud.base.business.order.domain.BasOrder;
import com.alibaba.cloud.base.business.order.service.BasOrderService;
import com.alibaba.cloud.base.constant.BaseConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.framework.wrapper.RedisWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BasOrderServiceImpl implements BasOrderService {

    @Autowired
    private BasOrderMapper basOrderMapper;

    @Autowired
    private RedisWrapper<String, Object> redisWrapper;

    @Override
    public List<BasOrder> getAll() {

        QueryWrapper<BasOrder> wrapper = new QueryWrapper<>();
        List<BasOrder> basOrderList = basOrderMapper.selectList(wrapper);

        return basOrderList;
    }

    @Override
    public List<BasOrder> getOrderListByType(String orderType) {
        String orderTypeKey = BaseConstant.BASE_ORDER_TYPE_KEY + orderType;
        if (redisWrapper.hasKey(orderTypeKey)) {
            Object value = redisWrapper.getValue(orderTypeKey);
            List<BasOrder> basOrders = JSON.parseArray(value.toString(), BasOrder.class);
            return basOrders;
        }

        QueryWrapper<BasOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("item_type", orderType);
        List<BasOrder> basOrderList = basOrderMapper.selectList(wrapper);
        String basOrderListJSON = JSON.toJSONString(basOrderList);
        redisWrapper.putValueWithExpireTime(orderTypeKey, basOrderListJSON, BaseConstant.EXPIRE_TIME, TimeUnit.SECONDS);
        return basOrderList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(BasOrder basOrder) {
        basOrder.setCreateTime(new Date());
        basOrderMapper.insert(basOrder);
        redisWrapper.delWithKey(BaseConstant.BASE_ORDER_TYPE_KEY + basOrder.getItemType());
    }
}
